package my.engine.core;

import my.engine.objects.RequestBean;
import my.engine.objects.UrlMapping;
import my.engine.utils.SettingsUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: emikolenko
 * Date: 22.02.2008
 * Time: 14:19:11
 */
public class MainServlet extends HttpServlet {

    public void init() throws ServletException {
        super.init();
        FlowManager.parseMappings();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        RequestBean requestBean = FlowManager.getRequestBean(request);
        String lang = requestBean.getLang();

        FlowManager.prepareLocale(request, lang);

        UrlMapping mapping = getMappings().get(requestBean.getView());
        if (mapping != null) {

            //List<PathNode> path;
            for (AbstractPathHandler handler : mapping.getHandlers()) {
                handler.processRequest(request, response, requestBean);
                /*if (handler.continuePocess()) {
                    path = handler.getResourcePath();
                }*/
            }

            FlowManager.prepareLangs(request);

            request.setAttribute("includeHeader", mapping.getHeader());
            request.setAttribute("includeMenu", mapping.getMenu());
            request.setAttribute("includeView", mapping.getView());
            request.setAttribute("includeFooter", mapping.getFooter());
            request.getRequestDispatcher(mapping.getTemplate()).forward(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/public/" + lang + "/" + FlowManager.defaultUrl);
        }
    }

    protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        doGet(httpServletRequest, httpServletResponse);
    }

    private Map<String, UrlMapping> getMappings() {
        return FlowManager.getMappings();
    }

}
